var ctx, width, height, r;

function init(ctx1, obj) {
  ctx = ctx1;
  width = obj.width;
  height = obj.height;
  r = obj.width / 2 - 20;
  drawClock();
  setInterval(drawClock, 500);
}
function run() {
  var date = new Date();
  var h = date.getHours();
  var m = date.getMinutes();
  var s = date.getSeconds();
  drawHours(h, m, s);
  drawMinute(m, s);
  drawSeconds(s);
  drawCenter();
  ctx.restore();
}

// 画表
function drawClock() {
  ctx.clearRect(0, 0, width, height);
  ctx.save();
  ctx.translate(r + 20, r + 20);
  drawCircle();
  drawScale();
  run();
  ctx.restore();
}
// 画圆
function drawCircle() {
  ctx.beginPath();
  ctx.lineWidth = "6";
  ctx.arc(0, 0, r, 0, Math.PI * 2);
  ctx.stroke();
}
// 画刻度和小时
function drawScale() {
  // 刻度
  for (var i = 0; i < 60; i++) {
    // 弧度
    var radian = ((2 * Math.PI) / 60) * i;
    var x = r * Math.cos(radian);
    var y = r * Math.sin(radian);
    ctx.beginPath();
    // 如果能被5整除
    if (i % 5 == 0) {
      ctx.fillStyle = "red";
    } else {
      ctx.fillStyle = "#ccc";
    }
    ctx.arc(x, y, 2, 0, 2 * Math.PI);
    ctx.fill();
  }
  // 画数字
  var hourList = [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2];
  for (var i = 0; i < 12; i++) {
    var radian = ((2 * Math.PI) / 12) * i;
    var x = (r - 20) * Math.cos(radian);
    var y = (r - 20) * Math.sin(radian);
    ctx.textAlign = "center";
    ctx.textBaseline = "middle";
    ctx.font = "26px 微软雅黑";
    ctx.fillStyle = "#333";
    ctx.beginPath();
    ctx.fillText(hourList[i], x, y);
    ctx.fill();
  }
}
// 画中间的帽（中心点）
function drawCenter() {
  ctx.save();
  ctx.beginPath();
  ctx.fillStyle = "#fff";
  ctx.arc(0, 0, 5, 0, 2 * Math.PI);
  ctx.fill();
  ctx.restore();
}
// 画秒针
function drawSeconds(s) {
  ctx.save();
  ctx.beginPath();
  ctx.rotate(((2 * Math.PI) / 60) * s);
  ctx.strokeStyle = "#ff0000";
  ctx.lineCap = "round";
  ctx.moveTo(0, r * 0.9 * 0.2);
  ctx.lineTo(0, -r * 0.9 * 0.8);
  ctx.stroke();
  ctx.restore();
}
// 画分针
function drawMinute(m, s) {
  ctx.save();
  ctx.beginPath();
  var radianM = ((2 * Math.PI) / 60) * m;
  var radianS = ((2 * Math.PI) / 60 / 60) * s;
  ctx.rotate(radianM + radianS);
  ctx.strokeStyle = "#333333";
  ctx.lineCap = "round";
  ctx.moveTo(0, r * 0.8 * 0.2);
  ctx.lineTo(0, -r * 0.8 * 0.8);
  ctx.stroke();
  ctx.restore();
}
// 画时针
function drawHours(h, m, s) {
  ctx.save();
  ctx.beginPath();
  var radianH = ((2 * Math.PI) / 12) * h;
  var radianM = ((2 * Math.PI) / 12 / 60) * m;
  var radianS = ((2 * Math.PI) / 12 / 60 / 60) * s;
  ctx.rotate(radianH + radianM + radianS);
  ctx.strokeStyle = "#333";
  ctx.lineCap = "round";
  ctx.moveTo(0, r * 0.6 * 0.2);
  ctx.lineTo(0, -r * 0.6 * 0.8);
  ctx.stroke();
  ctx.restore();
}
export { init };